/* eslint-disable no-constant-condition */
import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'
import { getSuggestion } from '@/store/actions/search'
import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useDebounceFn } from 'ahooks'
import { useEffect, useState } from 'react'
import { heighLight } from '@/utils'
import { getHistory, setHistory } from '@/utils/storageHistory'
// import { useRef } from 'react'
// import { useDispatch } from 'react-redux'

const SearchPage = () => {
  const history = useHistory()
  const [keyword, setKeyword] = useState('')
  const [searchHistory, setSearchHistory] = useState<string[]>(() => getHistory())
  const [suggestion, setSuggestion] = useState<string[]>([])
  //   const dispatch = useDispatch()
  // 准备定时器
  //   const timerRef = useRef(-1)
  //   const onChange = async (val: string) => {
  //     // 清空定时器
  //     window.clearTimeout(timerRef.current)
  //     // 新开一个定时器
  //     timerRef.current = window.setTimeout(async () => {
  //       // 发请求，取回搜索建议
  //       const res = await getSuggestion(val)
  //       console.log('val', val, res)
  //     }, 500)
  //   }
  const onChange = async (val: string) => {
    setKeyword(val)
    run()
  }
  const { run } = useDebounceFn(async () => {
    // 1. 发请求，取回搜索建议
    if (!keyword) {
      setSuggestion([])
      return
    }
    const res = await getSuggestion(keyword)
    const suggestion = res.data.data.options
    // console.log(suggestion)
    setSuggestion(suggestion)
  }, { wait: 500 })

  // 1. 追加历史搜索记录
  // 2. 页面跳转
  const onSearch = (keyword: string) => {
    console.log('追加历史搜索记录', keyword)
    // 1. 删除现有的
    const idx = searchHistory.findIndex(it => it === keyword)
    if (idx !== -1) {
      searchHistory.splice(idx, 1)
    }
    // 2. 追加到第一个
    const newList = [keyword, ...searchHistory]
    setSearchHistory(newList)

    // 3. 跳转页面
    setTimeout(() => {
      history.push('/search/result?keyword=' + keyword)
    }, 100)
  }
  // 删除一项
  const delSearchHistory = (idx: number) => {
    searchHistory.splice(idx, 1)
    // setSearchHistory(searchHistory)

    setSearchHistory([...searchHistory])
  }

  // 当searchHistory变化时，做持久化
  useEffect(() => {
    setHistory(searchHistory)
  }, [searchHistory])

  // const pStr = '<img src="xxxxxx黑客的地址"/>'
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={<span className="search-text" onClick={() => { onSearch(keyword) }}>搜索</span>}
      >
        <SearchBar value={keyword} onChange={ onChange } placeholder="请输入关键字搜索" />
      </NavBar>

      {!keyword && (
        <div
          className="history"
          style={{
            display: false ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={() => setSearchHistory([])}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {
              searchHistory.map((it, idx) => (
              <span key={it} className="history-item">
                <span onClick={() => onSearch(it)} className="text-overflow">{it}</span>
                <Icon onClick={() => delSearchHistory(idx)} type="iconbtn_essay_close" />
              </span>
              ))
            }
          </div>
        </div>
      )}

      <div className={classnames('search-result', keyword ? 'show' : '')}>
        {
            suggestion.map((str, idx) => (
            <div key={idx} className="result-item" >
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                onClick={() => onSearch(str)}
                className="result-value text-overflow"
                dangerouslySetInnerHTML={{ __html: heighLight(str, keyword) }}
              ></div>
            </div>
            ))
        }
      </div>
    </div>
  )
}

export default SearchPage
